#pragma once

#include <QTcpServer>
#include <QTcpSocket>
#include <QHash>
#include "tcp_socket_client.h"

namespace infrastructure {
namespace io {

/**
 * @brief TCP服务器封装类
 * @details 管理多个TCP客户端连接
 */
class TcpSocketServer : public QTcpServer {
    Q_OBJECT

public:
    explicit TcpSocketServer(int numConnections = 10, QObject *parent = nullptr);
    ~TcpSocketServer();

    /**
     * @brief 设置最大连接数
     */
    void setMaxPendingConnections(int numConnections);

    /**
     * @brief 获取所有客户端连接
     */
    QHash<qint64, TcpSocketClient*> getClients() const { return tcpClient; }

    /**
     * @brief 获取当前连接数
     */
    int getConnectionCount() const { return nConnectCount; }

signals:
    /**
     * @brief 新客户端连接信号
     */
    void sig_connectClient(qint64 socketDescriptor, const QString &ip, quint16 port);

    /**
     * @brief 客户端断开连接信号
     */
    void sig_sockDisConnect(qint64 socketDescriptor, const QString &ip, quint16 port);

    /**
     * @brief 断开特定连接信号
     * @param socketDescriptor 套接字描述符，-1表示断开所有连接
     */
    void sentDisConnect(qint64 socketDescriptor);

public slots:
    /**
     * @brief 断开所有连接
     */
    void clear();

protected:
    /**
     * @brief 处理新连接
     */
    void incomingConnection(qintptr socketDescriptor) override;

private slots:
    /**
     * @brief 处理socket断开连接
     */
    void sockDisConnectSlot(qint64 socketDescriptor, const QString &ip, quint16 port, QThread *th);

private:
    QHash<qint64, TcpSocketClient*> tcpClient;  // 管理所有连接的客户端
    int maxConnections;                         // 最大连接数
    int nConnectCount;                          // 当前连接数
};

} // namespace io
} // namespace infrastructure
